package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    GraphInfoService graphInfoService;
    @Autowired
    ApartmentFacilityService apartmentFacilityService;
    @Autowired
    ApartmentLabelService apartmentLabelService;
    @Autowired
    ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    ProvinceInfoService provinceInfoService;
    @Autowired
    CityInfoService cityInfoService;
    @Autowired
    DistrictInfoService districtInfoService;
    @Autowired
    ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    GraphInfoMapper graphInfoMapper;
    @Autowired
    LabelInfoMapper labelInfoMapper;
    @Autowired
    FacilityInfoMapper facilityInfoMapper;
    @Autowired
    FeeValueMapper feeValueMapper;
    @Autowired
    RoomInfoMapper roomInfoMapper;
    @Override
    public void saveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {

        // 表单只提交省市区id，没有提交名称。需要业务层处理下
        apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());
        super.saveOrUpdate(apartmentSubmitVo);
        //判断是否需要清理旧信息，需要先获取公寓的ID是否存在;
        //把自己的信息先保存的自己的表中，关联关系表进行重新修改
        if(apartmentSubmitVo.getId()!=null){
            //1.删除图片列表
            LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
            //获取关联公寓的图片
            graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            //获取对应公寓Id的图片
            graphQueryWrapper.eq(GraphInfo::getItemId,apartmentSubmitVo.getId());
            //删除
            graphInfoService.remove(graphQueryWrapper);
            //2.删除配套列表
            LambdaQueryWrapper<ApartmentFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
            facilityQueryWrapper.eq(ApartmentFacility::getApartmentId,apartmentSubmitVo.getId());
            apartmentFacilityService.remove(facilityQueryWrapper);
            //3.删除标签列表
            LambdaQueryWrapper<ApartmentLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
            labelQueryWrapper.eq(ApartmentLabel::getApartmentId,apartmentSubmitVo.getId());
            apartmentLabelService.remove(labelQueryWrapper);
            //4.删除杂费列表
            LambdaQueryWrapper<ApartmentFeeValue> feeValueQueryWrapper = new LambdaQueryWrapper<>();
            feeValueQueryWrapper.eq(ApartmentFeeValue::getApartmentId,apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(feeValueQueryWrapper);
        }
   //1.插入图片列表
        //得到获得图片的各个属性，封装成一个GraphVo实体集合
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        //设置一个数组集合遍历设置属性，加入到集合中，进行批量保存
        if(!CollectionUtils.isEmpty(graphVoList)){
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>();
            for(GraphVo graphVo : graphVoList){
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }
        //2.插入配套列表
        List<Long> facilityInfoIdList = apartmentSubmitVo.getFacilityInfoIds();
        if(!CollectionUtils.isEmpty(facilityInfoIdList)){
            ArrayList<ApartmentFacility> facilityList = new ArrayList<>();
            for(Long facilityId : facilityInfoIdList){
               ApartmentFacility apartmentFacility = new ApartmentFacility();
               apartmentFacility.setApartmentId(apartmentSubmitVo.getId());
               apartmentFacility.setFacilityId(facilityId);
               facilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(facilityList);
        }
        //3.插入标签列表
        List<Long> labelInfoIdList = apartmentSubmitVo.getLabelIds();
        if(!CollectionUtils.isEmpty(labelInfoIdList)){
            ArrayList<ApartmentLabel> labelList = new ArrayList<>();
            for(Long labelId : labelInfoIdList){
               ApartmentLabel apartmentLabel = new ApartmentLabel();
               apartmentLabel.setApartmentId(apartmentSubmitVo.getId());
               apartmentLabel.setLabelId(labelId);
               labelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(labelList);
        }
        //4.插入杂费列表
        List<Long> feeValueIdList = apartmentSubmitVo.getFeeValueIds();
        if(!CollectionUtils.isEmpty(feeValueIdList)){
            ArrayList<ApartmentFeeValue> apartmentFeeValues = new ArrayList<>();
            for(Long feeValueId : feeValueIdList){
                ApartmentFeeValue apartmentFeeValue = new ApartmentFeeValue();
                apartmentFeeValue.setApartmentId(apartmentSubmitVo.getId());
                apartmentFeeValue.setFeeValueId(feeValueId);
                apartmentFeeValues.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValues);
        }
    }

    @Override
    public IPage<ApartmentItemVo> pageApartmentItemByQuery(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageApartmentItemByQuery(page,queryVo);
    }

    @Override
    public ApartmentDetailVo getApartmentDtailById(Long id) {
        //1.查询ApartmentInfo,this继承的是ServiceImpl
        ApartmentInfo apartmentInfo = this.getById(id);
        if(apartmentInfo == null){
            return null;
        }
        //2.查询GraphInfo
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndId(ItemType.APARTMENT, id);
        //3.查询LabelInfo
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);
        //4.查询FacilityInfo
        List<FacilityInfo> facilityInfos = facilityInfoMapper.selectListByApartmentId(id);
        //5.查询FeeValue
        List<FeeValueVo> feeValues = feeValueMapper.selectListByApartmentId(id);

        ApartmentDetailVo adminApartmentDetailVo = new ApartmentDetailVo();
        BeanUtils.copyProperties(apartmentInfo,adminApartmentDetailVo);
        adminApartmentDetailVo.setGraphVoList(graphVoList);
        adminApartmentDetailVo.setLabelInfoList(labelInfoList);
        adminApartmentDetailVo.setFacilityInfoList(facilityInfos);
        adminApartmentDetailVo.setFeeValueVoList(feeValues);

        return adminApartmentDetailVo;
    }

    @Override
    public void removeApartmentById(Long id) {
        //公寓下会包含房间信息，因此在删除公寓时最好先判断一下该公寓下是否存在房间信息
        //若存在，则提醒用户先删除房间信息后再删除公寓信息
        /**LambdaQueryWrapper<RoomInfo> roomQueryWrapper = new LambdaQueryWrapper<>();
           roomQueryWrapper.eq(RoomInfo::getApartmentId, id);
           Long count = roomInfoMapper.selectCount(roomQueryWrapper);
           if (count > 0) {
       //直接为前端返回如下响应：先删除房间信息再删除公寓信息
       }*/
        //想要直接为前端返回响应，可利用前边配置的全局异常处理功能
        //（此处直接抛出异常，全局异常处理器捕获到异常后，便会直接为前端返回响应结果）
        // 为灵活设置响应信息，可自定义异常类
        LambdaQueryWrapper<RoomInfo> roomQueryWrapper = new LambdaQueryWrapper<>();
        roomQueryWrapper.eq(RoomInfo::getApartmentId, id);
        Long count = roomInfoMapper.selectCount(roomQueryWrapper);
        if (count > 0) {
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }
        //1.删除图片列表
        LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
        graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        //获取对应公寓Id的图片
        graphQueryWrapper.eq(GraphInfo::getItemId,id);
        //删除
        graphInfoService.remove(graphQueryWrapper);
        //2.删除配套列表
        LambdaQueryWrapper<ApartmentFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
        facilityQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(facilityQueryWrapper);
        //3.删除标签列表
        LambdaQueryWrapper<ApartmentLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
        labelQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(labelQueryWrapper);
        //4.删除杂费列表
        LambdaQueryWrapper<ApartmentFeeValue> feeValueQueryWrapper = new LambdaQueryWrapper<>();
        feeValueQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(feeValueQueryWrapper);
        //删除自身
        super.removeById(id);
    }
}




